package com.system.demo.controller;

import com.system.demo.doMain.entity.LogInResult;
import com.system.demo.doMain.entity.User;
import com.system.demo.doMain.request.LoginRequest;
import com.system.demo.service.UserService;
import com.system.demo.utils.JWTUtils;
import com.system.demo.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public JsonData login(@RequestBody LoginRequest loginRequest){
        User user=userService.findUser(loginRequest.getName(),loginRequest.getPassword());
        if (user!=null){
            LogInResult result=new LogInResult();
            result.setRoles("admin");
            result.setUser(user);
            result.setToken(JWTUtils.geneJsonWebToken(user));
            result.setExpiredAt(11000);
            return JsonData.buildSuccess("success",result);
        }
        return JsonData.buildError(0,"登录失败！");
    }

    @GetMapping("/list_user")
    public JsonData listUser(){
        List<User>userList=userService.list();
        return JsonData.buildSuccess(null,userList);
    }

    @PostMapping("/register")
    public JsonData register(@RequestBody Map<String,String> userInfo){
        int rows=userService.save(userInfo);
        return rows==1? JsonData.buildSuccess("注册成功",null):JsonData.buildError("注册失败");
    }

    @GetMapping("routes")
    public JsonData routes(){
        return new JsonData(0,null,null);
    }

    @PostMapping("/find_user_by_name")
    public JsonData findUserByName( String name){
        User user=userService.findUserByName(name);
        System.out.println(user);
        return user==null? JsonData.buildError("没有改用户"):JsonData.buildSuccess("",user);
    }

}
